const express = require('express');
const router = express.Router();
const weatherService = require('../services/weatherService');
const { validateInput } = require('../utils/validation');

/**
 * 天气API路由
 * 提供天气查询相关的接口
 */

/**
 * GET /api/weather/current
 * 获取当前IP位置的天气信息
 */
router.get('/current', async (req, res, next) => {
    try {
        // 检查天气服务配置
        if (!weatherService.checkWeatherConfig()) {
            return res.status(503).json({
                success: false,
                error: '天气服务暂时不可用，请稍后重试'
            });
        }

        const weatherData = await weatherService.getCurrentWeather();
        res.json(weatherData);

    } catch (error) {
        next(error);
    }
});

/**
 * GET /api/weather/city/:cityName
 * 根据城市名称获取天气信息
 */
router.get('/city/:cityName', async (req, res, next) => {
    try {
        const { cityName } = req.params;

        // 验证城市名称
        const validation = validateInput({ city: cityName }, {
            city: { required: true, type: 'string', minLength: 1, maxLength: 20 }
        });

        if (!validation.isValid) {
            return res.status(400).json({
                success: false,
                error: validation.errors.join(', ')
            });
        }

        // 检查天气服务配置
        if (!weatherService.checkWeatherConfig()) {
            return res.status(503).json({
                success: false,
                error: '天气服务暂时不可用，请稍后重试'
            });
        }

        const weatherData = await weatherService.getWeatherByCity(cityName);
        res.json(weatherData);

    } catch (error) {
        next(error);
    }
});

/**
 * POST /api/weather/query
 * 根据查询参数获取天气信息
 * 支持城市名称、城市ID、IP地址查询
 */
router.post('/query', async (req, res, next) => {
    try {
        const { city, cityid, ip } = req.body;

        // 至少需要一个查询参数
        if (!city && !cityid && !ip) {
            return res.status(400).json({
                success: false,
                error: '请提供城市名称、城市ID或IP地址中的至少一个参数'
            });
        }

        // 验证输入参数
        const validationRules = {};
        if (city) validationRules.city = { type: 'string', minLength: 1, maxLength: 20 };
        if (cityid) validationRules.cityid = { type: 'string', pattern: /^\d+$/ };
        if (ip) validationRules.ip = { type: 'string', pattern: /^(\d{1,3}\.){3}\d{1,3}$/ };

        const validation = validateInput(req.body, validationRules);
        if (!validation.isValid) {
            return res.status(400).json({
                success: false,
                error: validation.errors.join(', ')
            });
        }

        // 检查天气服务配置
        if (!weatherService.checkWeatherConfig()) {
            return res.status(503).json({
                success: false,
                error: '天气服务暂时不可用，请稍后重试'
            });
        }

        // 构建查询选项
        const queryOptions = {};
        if (cityid) queryOptions.cityid = cityid;
        else if (city) queryOptions.city = city;
        else if (ip) queryOptions.ip = ip;

        const weatherData = await weatherService.getWeather(queryOptions);
        res.json(weatherData);

    } catch (error) {
        next(error);
    }
});

/**
 * GET /api/weather/config
 * 检查天气服务配置状态
 */
router.get('/config', (req, res) => {
    const isConfigured = weatherService.checkWeatherConfig();
    res.json({
        success: true,
        data: {
            configured: isConfigured,
            message: isConfigured ? '天气服务已配置' : '天气服务需要配置APPID和APPSECRET'
        }
    });
});

module.exports = router;